#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstdlib>

void Usage(std::string proc)
{
    std::cout << "Usage: \n\t " << proc << "server_ip  "
              << "server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock create error:" << errno << std::endl;
        return 1;
    }
    while (1)
    {
        std::string message;
        std::cout << "输入# ";
        std::cin >> message;
        sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(atoi(argv[2]));
        server.sin_addr.s_addr = inet_addr(argv[1]);
        sendto(sock, message.c_str(), message.size(), 0, (sockaddr *)&server, sizeof(server));
        sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buffer[1024];
        recvfrom(sock, buffer, sizeof(buffer), 0, (sockaddr *)&tmp, &len);
        std::cout << buffer << std::endl;
    }
    return 0;
}